package wxapp

import (
	"encoding/json"
	"fmt"
	"huling/utils/results"
	utils "huling/utils/tool"
	"io/ioutil"
	"net/url"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gohouse/gorose/v2"
)

// 保存选择的内置产品
func SaveSelectProduct(context *gin.Context) {
	//获取post传过来的data
	body, _ := ioutil.ReadAll(context.Request.Body)
	var parameter map[string]interface{}
	_ = json.Unmarshal(body, &parameter)
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	//批量提交
	DB().Table("wxapp_product_select").Where("wxuid", user.ID).Delete()
	save_arr := []map[string]interface{}{}
	for _, val := range parameter["productids"].([]interface{}) {
		marr := map[string]interface{}{"wxuid": user.ID, "product_id": val}
		save_arr = append(save_arr, marr)
	}
	res, err := DB().Table("wxapp_product_select").Data(save_arr).Insert()
	if err != nil {
		results.Failed(context, "添加失败", err)
	} else {
		results.Success(context, "添加成功！", res, nil)
	}
}

// 保存自定义产品
func SaveProduct(context *gin.Context) {
	//获取post传过来的data
	body, _ := ioutil.ReadAll(context.Request.Body)
	var parameter map[string]interface{}
	_ = json.Unmarshal(body, &parameter)
	//当前用户
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	var f_id float64 = 0
	if parameter["id"] != nil {
		f_id = parameter["id"].(float64)
	}
	if f_id == 0 {
		parameter["uid"] = user.ID
		parameter["from"] = "my"
		parameter["createtime"] = time.Now().Unix()
		addId, err := DB().Table("wxapp_product").Data(parameter).InsertGetId()
		if err != nil {
			results.Failed(context, "添加失败", err)
		} else {
			results.Success(context, "添加成功！", addId, nil)
		}
	} else {
		res, err := DB().Table("wxapp_product").
			Data(parameter).
			Where("id", f_id).
			Update()
		if err != nil {
			results.Failed(context, "更新失败", err)
		} else {
			results.Success(context, "更新成功！", res, nil)
		}
	}
}

// 获取产品列表
func GetProductList(context *gin.Context) {
	//类型
	from := context.DefaultQuery("from", "my")
	keyWord := context.DefaultQuery("searchword", "")
	getuser, _ := context.Get("user")
	user := getuser.(*utils.UserClaims)
	if from == "my" {
		plist, err := DB().Table("wxapp_product").Where("uid", user.ID).Order("id desc").Get()
		if err != nil {
			results.Failed(context, "获取自己添加产品列表失败!", err)
		} else {
			if plist == nil {
				plist = make([]gorose.Data, 0)
			}
			results.Success(context, "获取自己添加产品列表！", plist, nil)
		}
	} else { //获取后台指定的产品
		MDB := DB().Table("wxapp_product").Where("from", "built").Fields("id,image,name,des,price,commission,link_type,link,appid,path,extraData,createtime")
		if keyWord != "" {
			MDB.Where("name", "like", "%"+keyWord+"%")
		}
		plist, err := MDB.Order("id desc").Get()
		if err != nil {
			results.Failed(context, "获取内置产品列表失败!", err)
		} else {
			mobile, _ := DB().Table("wxapp_user").Where("id", user.ID).Value("mobile")
			s_plist := make([]interface{}, 0)
			if plist != nil {
				product_ids, _ := DB().Table("wxapp_product_select").Where("wxuid", user.ID).Pluck("product_id")
				for _, val := range plist {
					if resd := IsContain_str(product_ids.([]interface{}), fmt.Sprintf("%s%v", "", val["id"])); resd == true {
						val["checked"] = true
					}
					if val["link_type"] == "wxapp" {
						if find := strings.Contains(val["path"].(string), "?"); find {
							val["path"] = fmt.Sprintf("%s&mobile=%s", val["path"], mobile)
						} else {
							val["path"] = fmt.Sprintf("%s?mobile=%s", val["path"], mobile)
						}
					}
					s_plist = append(s_plist, val)
				}
			}
			//获取猫车服产品
			var access_parameter map[string]interface{}
			var mm_product []interface{}
			qhttp := "http://114.117.246.205:7001/publicapi/sitegoods/sitegoodslist2?token=pxd119"
			if keyWord != "" {
				qhttp = fmt.Sprintf("http://114.117.246.205:7001/publicapi/sitegoods/sitegoodslist2?token=pxd119&keyWord=%s", url.QueryEscape(keyWord))
			}
			mmcf_data, err := Get_x(qhttp)
			if err != nil {
				mm_product = make([]interface{}, 0)
			} else {
				if err := json.Unmarshal([]byte(mmcf_data), &access_parameter); err == nil {
					if access_parameter["data"] != nil {
						var item map[string]interface{}
						product_ids_mm, _ := DB().Table("wxapp_product_select").Where("wxuid", user.ID).Pluck("product_id")
						for _, val := range access_parameter["data"].([]interface{}) {
							b_val, _ := json.Marshal(val)
							json.Unmarshal([]byte(b_val), &item)
							var checkeds bool = false
							if resd := IsContain_str(product_ids_mm.([]interface{}), fmt.Sprintf("%s%v", "mm_", item["id"])); resd == true {
								checkeds = true
							}
							tim, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s%s", "", item["createTime"]))
							mm_product = append(mm_product, map[string]interface{}{
								"id":         fmt.Sprintf("%s%v", "mm_", item["id"]),
								"image":      item["cover"],
								"name":       item["title"],
								"price":      item["price"],
								"commission": item["commission"],
								"des":        "",
								"checked":    checkeds,
								"link_type":  "wxapp",
								"appid":      "wx31d612c4b628d5cb",
								"path":       fmt.Sprintf("pages/product/detail/detail?goodId=%v&mobile=%s", item["id"], mobile),
								"extraData":  "",
								"createtime": tim.Unix(),
							})
						}
					}
				} else {
					mm_product = make([]interface{}, 0)
				}
			}
			results.Success(context, "获取内置产品列表1！", mergeArr(s_plist, mm_product), mmcf_data)
		}
	}
}

// 删除产品
func DelProduct(context *gin.Context) {
	id := context.DefaultQuery("id", "0")
	//获取post传过来的data
	res2, err := DB().Table("wxapp_product").Where("id", id).Delete()
	if err != nil {
		results.Failed(context, "删除失败", err)
	} else {
		results.Success(context, "删除成功！", res2, nil)
	}
}

// 获取产品数据-编辑
func GetProduct(context *gin.Context) {
	id := context.DefaultQuery("id", "0")
	//获取post传过来的data
	data, err := DB().Table("wxapp_product").Where("id", id).First()
	if err != nil {
		results.Failed(context, "获取产品数失败", err)
	} else {
		results.Success(context, "获取产品数据", data, nil)
	}
}
